package net.begincode.web.user;

import com.google.common.base.Preconditions;
import net.begincode.bean.UserBaseInfo;
import net.begincode.bean.param.LoginParam;
import net.begincode.biz.UserBiz;
import net.begincode.blog.bean.vo.BlogBaseInfo;
import net.begincode.blog.entity.User;
import net.begincode.blog.enums.BlogFlagEnum;
import net.begincode.common.ApiResponse;
import net.begincode.common.CheckCodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("/user/")
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Resource
    private UserBiz userBiz;

    /**
     * 获取验证码
     */
    @RequestMapping(value = "checkCode", method = RequestMethod.GET)
    public void checkCode(HttpServletRequest req, HttpServletResponse response) {
        // 调用工具类生成的验证码和验证码图片
        Map<String, Object> codeMap = CheckCodeUtil.generateCodeAndPic();
        // 将四位数字的验证码保存到Session中。
        HttpSession session = req.getSession();
        //验证码存到session了
        session.setAttribute("code", codeMap.get("code").toString());
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -1);
        response.setContentType("image/jpeg");
        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos;
        try {
            sos = response.getOutputStream();
            ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            LOGGER.error("UserController.checkCode.Error", e);
        }
    }

    /**
     * 登录
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ModelAndView login(LoginParam loginParam, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        Preconditions.checkNotNull(loginParam, "参数不能为空");
        Preconditions.checkArgument(!StringUtils.isEmpty(loginParam.getCheckCode()), "验证码不能为空");
        Preconditions.checkArgument(!StringUtils.isEmpty(loginParam.getPwd()), "密码不能为空");
        Preconditions.checkArgument(!StringUtils.isEmpty(loginParam.getEmail()), "邮箱不能为空");
        // 将四位数字的验证码保存到Session中。
        HttpSession session = request.getSession();
        Object checkCode = session.getAttribute("code");
        if (checkCode == null || !Objects.equals(checkCode.toString(), loginParam.getCheckCode())) {
            LOGGER.error("验证码不正确");
            modelAndView.addObject("errMsg", "验证码不正确");
            modelAndView.setViewName("login");
            return modelAndView;
        }
        User user = userBiz.checkUser(loginParam.getEmail(), loginParam.getPwd());
        if (user != null) {
            modelAndView.setViewName("admin");
        } else {
            modelAndView.addObject("errMsg", "密码验证失败");
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }

    /**
     * 退出
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public ModelAndView logout(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @RequestMapping(value = "/active", method = RequestMethod.POST)
    @ResponseBody
    public ApiResponse<List<UserBaseInfo>> activeUser(){
        List<UserBaseInfo> userBaseInfos =  userBiz.queryActiveUser(10);
        if(CollectionUtils.isEmpty(userBaseInfos)){
            return ApiResponse.fail("没有推荐信息");
        }
        return ApiResponse.success(userBaseInfos);
    }
}
